package com.dailyblue.java.spring.boot.jwt.interceptor;

import com.dailyblue.java.spring.boot.jwt.exception.NotLoginException;
import com.dailyblue.java.spring.boot.jwt.util.JwtConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// 负责拦截用户请求的，如果登陆了，可以访问，如果没登陆就报错
@Component
@Slf4j
public class CheckLoginInterceptor implements HandlerInterceptor {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("开始校验用户是否登陆....");
        String token = request.getHeader("token");
        log.info("用户发送的token是：{}", token);
        if (token == null) {
            throw new NotLoginException("用户未登陆");
        }
        boolean b = JwtConfig.checkToken(token);
        if (!b) {
            throw new NotLoginException("");
        }
        String id = JwtConfig.getMemberIdByJwtToken(request);
        // 判断和服务器中存放的是否一致
        ValueOperations<String, String> value = stringRedisTemplate.opsForValue();
        String token1 = value.get("token:" + id);
        if (!token.equals(token1)) {
            throw new NotLoginException("");
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
